package com.zzedu.framework.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 基于时间方式 redis 发号器
 */
@Component
public class RedisIdWorker {
    @Autowired
    private RedisTemplate redisTemplate;

    private static final long BEGIN_TIMESTAMP = 1640995200L;
    private static final int COUNT_BITS = 32;
    /**
     * 购物订单
     */
    public static String ORDER_KEY_PREFIX = "order";

    /**
     * 售后订单
     */
    public static String SALE_AFTER_ORDER_KEY_PREFIX = "sale_after_order";

    /**
     * 支付流水订单
     */
    public static String PAY_ORDER_KEY_PREFIX = "pay_order";
    /**
     * 退款流水订单
     */
    public static String REFUND_ORDER_KEY_PREFIX = "refund_order";
    public long generateNextId(String keyPrefix) {
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd:HH:mm"));
        String key = "icr:" + keyPrefix + ":" + date;
        long count = redisTemplate.opsForValue().increment(key);
        // 70秒后过期
        redisTemplate.expire(key, 65, TimeUnit.SECONDS);
        return timestamp << COUNT_BITS | count;
    }
}
